import { handleSql } from 'src/support/untils/sql';
import { FindAllCarBrandDto } from './dto/findAll-car_brand.dto';
import { CarBrand } from './car_brand.entity';
import { Injectable } from '@nestjs/common';
import { CreateCarBrandDto } from './dto/create-car_brand.dto';
import { UpdateCarBrandDto } from './dto/update-car_brand.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class CarBrandService {
  constructor(
    @InjectRepository(CarBrand)
    private carBrandRepository: Repository<CarBrand>,
  ) {}

  async create(createCarBrandDto: CreateCarBrandDto) {
    const entityDto = this.carBrandRepository.create(createCarBrandDto);
    return this.carBrandRepository.save(entityDto);
  }

  async findAll(findAllCarBrandDto: FindAllCarBrandDto) {
    const { limit = 10, page = 1, ...params } = findAllCarBrandDto;
    const where = handleSql(params);
    const result = await this.carBrandRepository.findAndCount({
      where: where,
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      list: result[0],
      total: result[1],
    };
  }

  async findAllCarType() {
      let indexList = ['A','B',"C",'D','E',"F",'G','H',"I",'J','K',"L",'M','N',"O",'P','Q',"R",'S','T',"U",'V',"W",'S','Y',"Z"]
      let brand_list = []
      indexList.push("#")
      brand_list.push([{
        first_letter:"#",
        id:"",
        name:"全部"
      }])
      indexList.forEach(item => {
        brand_list.push([]);
      });
    const result = await this.carBrandRepository.findAndCount();
    result[0].forEach((brandItem) => {
      const index = indexList.indexOf(brandItem.first_letter);
      if (index !== -1) {
        brand_list[index].push(brandItem);
      }
    })

    return {
      indexList: indexList,
      brand_list: brand_list,
    };
  }


  findOne(id: number) {
    return this.carBrandRepository.findOneById(id);
  }

  async update(id: number, updateCarBrandDto: UpdateCarBrandDto) {
    const hasEntriy = await this.carBrandRepository.findOneById(id);
    if (!hasEntriy) {
      return;
    }
    const updateInfo = this.carBrandRepository.merge(
      hasEntriy,
      updateCarBrandDto,
    );
    return this.carBrandRepository.save(updateInfo);
  }

  remove(id: number) {
    return this.carBrandRepository.delete(id);
  }

  async getTotal() {
    const result = await this.carBrandRepository.count();
    return result;
  }
}
